package com.hanter.android.radlib.util;

public class StringUtils {

    public static String strToHex(String str) {
        return bytesToHex(str.getBytes());
    }

    public static String hexToStr(String hex) {
        return new String(hexToBytes(hex));
    }

    public static byte[] hexToBytes(String hex) {
        int len = hex.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++)
            result[i] = Integer.valueOf(hex.substring(2 * i, 2 * i + 2), 16).byteValue();
        return result;
    }

    public static String bytesToHex(byte[] buf) {
        if (buf == null)
            return "";
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (byte e : buf) {
            appendHex(result, e);
        }
        return result.toString();
    }

    private final static String HEX = "0123456789ABCDEF";

    private static void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }

}
